/**
 * gislin 2017年7月11日
 */
package com.btcode.db.executer;

import com.btcode.db.config.DataBaseConfig;
import com.btcode.db.connection.IConnectionGetter;
import com.btcode.db.conver.DefaultValueConver;
import com.btcode.db.conver.IValueConver;
import com.btcode.db.result.PageResult;
import com.btcode.db.result.Row;
import com.btcode.db.sqlparameter.PageInfo;
import com.btcode.db.sqlparameter.SQLParameterList;
import com.btcode.exception.MsgException;

import java.util.List;

/**
 * @author gislin 2017年7月11日
 */
public class DmDataExecuter extends BaseDataExecuter {

    private IConnectionGetter connectionGetter;

    @Override
    public void close() {
        this.connectionGetter.close();
    }

    public DmDataExecuter(DataBaseConfig config, IConnectionGetter connectionGetter) {
        super(config, connectionGetter);
    }

    @Override
    public PageResult queryListPage(String sql, SQLParameterList parms, PageInfo pageInfo) {

        if(pageInfo == null){
            throw new MsgException("分页信息pageInfo不能为空");
        }

        if(pageInfo.getPageSize() >= 1000){
            //throw new MsgException("pageInfo.getPageSize:"+pageInfo.getPageSize()+",分页信息：PageSize不能超过1000");
        }

        String countSQL = " SELECT COUNT(*) FROM (" + sql + ") t ";
        Object countObj = queryScalar(countSQL, parms);

        IValueConver conver = new DefaultValueConver();
        int recordCount = conver.converToInteger(countObj);
        int pageCount = (int) Math.ceil(recordCount * 1.0 / pageInfo.getPageSize());
        int pageIndex = pageInfo.getPageIndex() > pageCount ? pageCount : pageInfo.getPageIndex();
        int offset = (pageIndex - 1) * pageInfo.getPageSize();

        if (pageIndex == 0) {
            pageIndex = 1;
        }

        pageInfo.setPageCount(pageCount);
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setRecordCount(recordCount);

        String pageSql = " SELECT * FROM ( SELECT t.*,ROWNUM oracle_rn FROM (" + sql
            + ") t ) t1 WHERE oracle_rn <= " + (pageInfo.getPageSize() + offset)
            + " AND oracle_rn > " + offset;

        List<Row> rows = executeQuery(pageSql, parms);

        PageResult result = new PageResult(pageInfo, rows);

        return result;
    }

}
